
//手动交易api加密串
import jhttps from "@/_js/https"
import jmodal from "@/_js/modal"
import jconfig from "@/_js/config"
import jnavigator from "@/_js/navigator"

const weexFunction = weex.requireModule("WeexFunction")

var apiId = '';
var apiRsa = '';

var apiIdContract = '';
var apiRsaContract = '';
export default {
  
  isFunlvue(api) {
    //登录
    if(!jconfig.forceLogin()) return true; 
      
    //录入API
    if (!api.apiId) { 
      var nav = {'navColor':'#0c0c0c'};
      jnavigator.open('', 'home/ApiAdd', undefined, nav);
      return true; 
    } 

    return false;
  },

  delectApiRsaStr(isCntract) {
    if (isCntract) {
      apiIdContract = '';
      apiRsaContract = '';
    } else {
      apiId = '';
      apiRsa = '';
    }
  },

  gtApiRsaStr(api, isCntract, load, back) {
    isCntract ? 
    this.gtApiRsaContract(api, load, back) :
    this.gtApiRsa(api, load, back);
  },

  gtApiRsaContract(api, load, back) {

    if (!api.apiId) {
      back('');
      return;
    }

    if (apiRsaContract && api.apiId == apiIdContract) {
      back(apiRsaContract)
      return;
    }

    this.httpsGetPublicKey(api, true, load, (newApiId, rsa)=>{
      apiIdContract = newApiId;
      apiRsaContract = rsa;
      back(rsa);
    });
  },

  gtApiRsa(api, load, back) {

    if (!api.apiId) {
      back('');
      return;
    }
    
    if (apiRsa && api.apiId == apiId) {
      back(apiRsa)
      return;
    }
    
    this.httpsGetPublicKey(api, false, load, (newApiId, rsa)=>{
      apiId = newApiId;
      apiRsa = rsa;
      back(rsa);
    });
  },

  /********************************************** https*/
  httpsGetPublicKey(api, isCntract, load, back){
    var param = {'serverType':'manualServer'};
    jhttps.post("assetsV2/getPublicKey",param,true,(data)=>{

      if(data.status == 200){

        var publicKey = data.data.publicKey;
        var type = isCntract ? 'contract_usdt' : 'spot';
        var apiData = {'exchangeName':api.exchangeName , 
                       'type':type,
                       'apiId':api.apiId};
        for (let index = 0; index < api.param.length; index++) {
          var param = api.param[index];
          apiData[param.field] = param.value;
        }
        apiData = JSON.stringify(apiData);
        weexFunction.rsaEncrypt(apiData, publicKey, (rsa)=>{
          back(api.apiId, rsa);
        });
      } else {
        load && jmodal.toast(data.msg);
      }
    });
  },
}